package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

import static cn.itcast.nio.c2.ByteBufferUtil.debugAll;

/**
 * @ClassName ChnnelDemo06
 * @Description 多路复用
 * @Author tant
 * @Date 2025/3/12 11:23
 */
@Slf4j
public class ChannelDemo06 {
    public static void main(String[] args) {
        try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
            ssc.bind(new InetSocketAddress(8080));
            Selector selector = Selector.open();
            ssc.configureBlocking(false);
            SelectionKey sscKey = ssc.register(selector, 0, null);
            sscKey.interestOps(SelectionKey.OP_ACCEPT); //只关注accept事件
            while (true) {
                //select 方法, 没有事件发生，线程阻塞，有事件，线程才会恢复运行
                selector.select(); //监听Channel事件

                //处理事件, selectedKeys 内部包含了所有发生的事件
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iter = keys.iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    // 判断事件类型
                    if (key.isAcceptable()) {//连接事件
                        ServerSocketChannel c = (ServerSocketChannel) key.channel();
                        // 必须处理，事件发生后，要么处理，要么取消（cancel）
                        SocketChannel sc = c.accept();
                        sc.register(selector, SelectionKey.OP_READ);//绑定Channel事件
                        log.debug("{}", sc);
                    } else if (key.isReadable()) {//read事件
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(128);
                        int read = sc.read(buffer);
                        if (read == -1) {
                            key.cancel();
                            sc.close();
                        } else {
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                    // 处理完毕，必须将事件移除
                    iter.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

    